//
// Created by denglibin on 2019/6/24 0024.
//
/**栈的链式存储实现**/
#include <stdlib.h>
#include <stdio.h>
/**
 * 链表节点
 */
typedef struct stack_node
{
    int data;
    struct stack_node *next;
} StackNode;

/**
 * 栈
 */
typedef struct linked_stack
{
    StackNode *top; //栈顶（链表头部）
    int size;       //栈大小
} LinkedStack;

/**
 * 创建节点
 * @return
 */
static StackNode *createStackNode(int data)
{
    StackNode *node = (StackNode *)calloc(1, sizeof(StackNode));
    node->data = data;
    return node;
}

/**
 * 创建栈
 * @return
 */
static LinkedStack *createLinkedStack()
{
    LinkedStack *stack = (LinkedStack *)calloc(1, sizeof(LinkedStack));
    stack->top = NULL;
    stack->size = 0;
    return stack;
}

/**
 * 入栈
 * @param stack
 * @param data
 */
static void pushStack(LinkedStack *stack, int data)
{
    StackNode *node = createStackNode(data);
    node->next = stack->top;
    stack->top = node;
    stack->size++;
}

/**
 * 弹栈
 * @param stack
 * @return
 */
static int popStack(LinkedStack *stack)
{
    if (stack->size == 0)
    {
        printf("stack is empty");
        return -1;
    }
    int data = stack->top->data;
    stack->top = stack->top->next;
    stack->size--;
    free(stack->top);
    return data;
}
/**
 * 释放空间
 * @param stack
 */
static void freeStack(LinkedStack *stack)
{
    if (stack == NULL || stack->size == 0)
    {
        return;
    }
    StackNode *temp = stack->top;
    StackNode *next;
    while (stack->size)
    {
        next = temp->next;
        printf("free stack node %d\n", temp->data);
        free(temp);
        temp = next;
        stack->size--;
    }
}

int main21()
{
    LinkedStack *stack = createLinkedStack();
    for (int i = 0; i < 10; i++)
    {
        pushStack(stack, i);
    }
    while (stack->size)
    {
        printf("%d\n", popStack(stack));
    }
    freeStack(stack);
    return 0;
}